package com.sk.client.level1;


import com.sk.common.level1.MethodParamRpc;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * description：
 *
 * @author 孙文斌
 * @Date: 2021/1/27 9:24
 */
@Slf4j
public class ClientSocket {
    private String ip;
    private Integer port;
    public  ClientSocket(String ip,int port){
        this.ip = ip;
        this.port = port;
    }
    public Object invoke(MethodParamRpc methodParam) {
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeUTF(methodParam.getClassName());
            objectOutputStream.writeUTF(methodParam.getMethodName());
            objectOutputStream.writeObject(methodParam.getParameterTypes());
            objectOutputStream.writeObject(methodParam.getArguments());
            ObjectInputStream ObjectInputStream = new ObjectInputStream(inputStream);
            return ObjectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("socket operation fail,exception info :" + e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("socket close exception,exception info :" + e);
                }
            }
        }
        return null;
    }
}
